//
//  EditAddressViewController.m
//  Yanwei
//
//  Created by 刘文 on 17/5/4.
//  Copyright © 2017年 DCloud. All rights reserved.
//

#import "EditAddressViewController.h"
#import "EditAddressCell.h"
#import "AuthorCertificationCustomAddressActionSheet.h"
#import "NSString+Util.h"

typedef NS_ENUM(NSUInteger, EditAddressViewControllerType) {
    EditAddressNameType, // 姓名
    EditAddressPhoneType, // 电话
    EditAddressTypes, // 地址
    EditAddressDetailType, // 详细地址
};

@interface EditAddressViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, AuthorCertificationCustomAddressActionSheetDelegate>

@property (assign, nonatomic) EditAddressType editAddressType;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) UIView *tableFooterView;
@property (nonatomic, strong) AuthorCertificationCustomAddressActionSheet *authorCCustomAddressAS; // 自定义地址sheet
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic, strong) NSString *nameString;
@property (nonatomic, strong) NSString *phoneString;
@property (nonatomic, strong) NSString *detailAddressString;
@property (nonatomic, strong) NSString *addressString;
@property (nonatomic, strong) NSString *areaSid;
@property (nonatomic, strong) NSString *sid;
@property (nonatomic, assign) BOOL isDefault;

@end

@implementation EditAddressViewController

- (instancetype)initWithEditAddressType:(EditAddressType)type {
    self = [super init];
    if (self) {
        self.editAddressType = type;
    }
    return self;
}

- (void)_reLayout {
    if (self.editAddressType == EditAddressTypeEdit) {
        self.navigationView.title = @"编辑地址";
    } else if (self.editAddressType == EditAddressTypeAdd) {
        self.navigationView.title = @"新增地址";
    }
    
    __weakConfigure
    [self.navigationView addNavigationRightView:CGRectMake(0, 0, 55, 40)
                                      titleFont:APPFONT(14)
                                     titleColor:Color100
                                      titleText:@"保存"
                                        tapBack:^(UIView * _Nonnull v) {
                                            [__weakSelf saveAction];
                                        }];
    
    self.tableView.tableFooterView = self.tableFooterView;
    
    // 通过通知监听获取键盘的输入事件,适配5s中地址不能输入中文的bug
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textfieldDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)textfieldDidChange:(NSNotification *)noti {
    UITextField *textField = (UITextField *)noti.object;
    
    if (textField.tag == EditAddressNameType) {
        self.nameString = textField.text;
    } else if (textField.tag == EditAddressDetailType) {
        self.detailAddressString = textField.text;
    }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)saveAction {
    if (self.nameString.hasValue && self.phoneString.isPhone && self.areaSid.hasValue && self.detailAddressString.hasValue) {
        if (self.editAddressType == EditAddressTypeEdit) {
            [MuchStoreRequestManager storeEditAddress:self.sid areaSid:self.areaSid address:self.detailAddressString name:self.nameString phone:self.phoneString addressDefault:self.isDefault sucess:^(id  _Nonnull responseObject) {
                [self.navigationController popViewControllerAnimated:YES];
            } fail:^(NSString *error) {
            }];
        } else if (self.editAddressType == EditAddressTypeAdd) {
            [MuchStoreRequestManager storeSaveAddress:self.areaSid address:self.detailAddressString name:self.nameString phone:self.phoneString addressDefault:self.isDefault sucess:^(id  _Nonnull responseObject) {
                [self.navigationController popViewControllerAnimated:YES];
            } fail:^(NSString *error) {}];
        }
    } else {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"请确认信息已填写！"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - method
- (void)chooseAddress:(UITextField *)textfield {
    TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:self.authorCCustomAddressAS preferredStyle:TYAlertControllerStyleActionSheet];
    alertController.backgoundTapDismissEnable = YES;
    _authorCCustomAddressAS.isContainsDistrict = YES;
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)switchAction:(UISwitch *)sw {
    if (sw.on == YES) {
        sw.on = self.isDefault = NO;
    } else {
        sw.on = self.isDefault = YES;
    }
}


#pragma mark - <AuthorCertificationCustomAddressActionSheetDelegate>
/** 地址协议代理 */
- (void)getAuthorCertificationCustomAddressActionSheetString:(NSString *)addressASString areaSid:(NSString *)areaSid {
    self.areaSid = areaSid;
    self.addressString = addressASString;
    [self.tableView reloadData];
}


#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString * identifier = @"EditAddressCell";
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    EditAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[EditAddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    if (indexPath.row == EditAddressPhoneType) {
        cell.textField.keyboardType = UIKeyboardTypeNumberPad;
    }
    if (indexPath.row == EditAddressDetailType) {
        cell.lineHedden = YES;
    } else {
        cell.lineHedden = NO;
    }
    
    if (self.editAddressType == EditAddressTypeEdit) {
        switch (indexPath.row) {
            case EditAddressNameType:
                cell.textField.text = self.model.name;
                break;
            case EditAddressPhoneType:
                cell.textField.text = self.model.mobile;
                break;
            case EditAddressTypes:
                cell.textField.text = self.addressString;
                break;
            case EditAddressDetailType:
                cell.textField.text = self.detailAddressString;
                break;
            default:
                break;
        }
    } else if (self.editAddressType == EditAddressTypeAdd) {
        cell.placeholder = self.dataSourceArray[indexPath.row];
        switch (indexPath.row) {
            case EditAddressTypes:
                cell.textField.text = self.addressString;
                break;
            default:
                break;
        }
    }
    cell.textField.tag = indexPath.row;
    cell.textField.delegate = self;
    [cell.textField addTarget:self action:@selector(textFiledDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001f;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * view = [[UIView alloc] init];
    view.backgroundColor = Color244;
    return view;
}


#pragma mark - <UITextFieldDelegate>
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.tag == EditAddressTypes) {
        [self chooseAddress:textField];
        return NO;
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag == EditAddressNameType) {
        self.nameString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    } else if (textField.tag == EditAddressPhoneType) {
        UITextRange *selectedRange = textField.markedTextRange;
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        if (!position) {
            NSString *beginString = [textField.text stringByReplacingCharactersInRange:range withString:string];
            NSString *nowString = [NSString filterCharactor:beginString withRegex:@"[^a-zA-Z0-9\u4e00-\u9fa5]"];
            if (nowString.length >= 11) {
                self.phoneString = [nowString substringToIndex:11];
                textField.text = self.phoneString;
                
                return NO;
            }
        } else {}
    } else if (textField.tag == EditAddressDetailType) {
        self.detailAddressString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    }
    return YES;
}
- (void)textFiledDidChange:(UITextField *)textfield {
    if (textfield.tag == EditAddressNameType) {
        UITextRange *selectedRange = textfield.markedTextRange;
        UITextPosition *position = [textfield positionFromPosition:selectedRange.start offset:0];
        if (!position) {
            textfield.text = [NSString filterCharactor:textfield.text withRegex:@"[^a-zA-Z0-9\u4e00-\u9fa5]"];
            if (textfield.text.length >= 16) {
                jxt_showAlertMessage(@"请输入16位以内的称谓！");
                textfield.text = [textfield.text substringToIndex:16];
            }
        } else {
        }
    } else if (textfield.tag == EditAddressDetailType) {
        UITextRange *selectedRange = textfield.markedTextRange;
        UITextPosition *position = [textfield positionFromPosition:selectedRange.start offset:0];
        if (!position) {
            NSString *textStrings = [NSString filterCharactor:textfield.text withRegex:@"[^a-zA-Z0-9\u4e00-\u9fa5]"];
            if (textStrings.length >= 34) {
                jxt_showAlertMessage(@"请输入34位以内的名称！");
                textfield.text = [textfield.text substringToIndex:34];
            }
        } else {
        }
    }
}


#pragma mark - setting
- (void)setModel:(StoreAddressModel *)model {
    _model = model;
    
    self.sid = _model.sid;
    self.areaSid = _model.districtSid;
    self.nameString = _model.name;
    self.phoneString = _model.mobile;
    self.addressString = _model.areaMergedName;
    self.detailAddressString = _model.address;
    self.isDefault = _model.defaultSetting;
}


#pragma mark - 懒加载
- (UITableView *)tableView {
    if(_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = Color244;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellAccessoryNone;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.bottom.and.right.equalTo(self.view);
            make.top.equalTo(self.navigationView.mas_bottom);
        }];
    }
    return _tableView;
}

- (UIView *)tableFooterView {
    if (!_tableFooterView) {
        _tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 54)];
        _tableFooterView.backgroundColor = [UIColor clearColor];
        
        UIView *bgView = [UIView new];
        bgView.backgroundColor = [UIColor whiteColor];
        [_tableFooterView addSubview:bgView];
        [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.bottom.and.right.equalTo(self.tableFooterView);
            make.top.equalTo(self.tableFooterView).with.offset(10);
        }];
        
        UILabel *titleLabel = [UILabel new];
        titleLabel.textColor = Color34;
        titleLabel.font = APPFONT(14);
        titleLabel.textAlignment = NSTextAlignmentLeft;
        titleLabel.text = @"设置默认地址";
        [bgView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgView).with.offset(15);
            make.centerY.equalTo(bgView);
        }];
        
        UISwitch *switchControl = [[UISwitch alloc] init];
        switchControl.on = self.isDefault;
        [bgView addSubview:switchControl];
        [switchControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(bgView);
            make.size.mas_equalTo(CGSizeMake(46.0f, 30.0f));
            make.right.mas_equalTo(bgView).with.offset(- 21);
        }];
        switchControl.transform = CGAffineTransformMakeScale(0.75, 0.75);
        [switchControl setOnTintColor:Color175030];
        [switchControl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    }
    return _tableFooterView;
}
/** 自定义地址sheet */
- (AuthorCertificationCustomAddressActionSheet *)authorCCustomAddressAS {
    if (!_authorCCustomAddressAS) {
        _authorCCustomAddressAS = [[AuthorCertificationCustomAddressActionSheet alloc] initWithFrame:self.view.frame];
        _authorCCustomAddressAS.delegate = self;
    }
    return _authorCCustomAddressAS;
}
- (NSMutableArray *)dataSourceArray {
    if (!_dataSourceArray) {
        _dataSourceArray = [[NSMutableArray alloc] initWithArray:@[@"姓名", @"联系电话", @"省 市 区", @"详细地址，如街道、楼牌号等"]];
    }
    return _dataSourceArray;
}

@end
